package bosc.cn.controller;

import bosc.cn.server.InternalClientEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author tianshq
 * @date 2025/9/6 22:14
 * @description
 */
@RestController
@RequestMapping("/api/tunnel")
@Slf4j
public class TunnelController {

    @GetMapping("/clients")
    public ResponseEntity<Set<String>> getConnectedClients() {
        return ResponseEntity.ok(InternalClientEndpoint.getConnectedClients());
    }

    @PostMapping("/send")
    public ResponseEntity<String> sendMessageToClient(
            @RequestParam String clientId,
            @RequestParam String message) {

        String requestId = "admin-" + UUID.randomUUID().toString();
        boolean success = InternalClientEndpoint.forwardRequest(clientId, requestId, message);

        if (success) {
            return ResponseEntity.ok("消息已发送");
        } else {
            return ResponseEntity.status(404).body("客户端未连接或发送失败");
        }
    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("connectedClients", InternalClientEndpoint.getConnectedClients());
        status.put("clientCount", InternalClientEndpoint.getConnectedClients().size());
        return ResponseEntity.ok(status);
    }
}

